package com.lawyers.action;

import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.lawyers.common.DocumentoCompletoVO;
import com.lawyers.common.UserVO;
import com.lawyers.database.DBAcciones;
import com.lawyers.form.SubirDocumentoForm;

public class SubirDocumentoAction extends Action {

	private static Logger logger = Logger.getLogger(SubirTemplateAction.class);

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		SubirDocumentoForm subirTemplateForm = (SubirDocumentoForm) form;
		String accion = subirTemplateForm.getAccion();
		UserVO user = (UserVO) request.getSession().getAttribute("USUARIO");

		if (user == null)
			return mapping.findForward("login");

		if ("cargar".equalsIgnoreCase(accion)) {
			DocumentoCompletoVO doc = new DocumentoCompletoVO();
			doc.setAutos(subirTemplateForm.getAutos());
			doc.setFecha(subirTemplateForm.getFecha());
			doc.setUsuario(user.getIdUsuario());

			FormFile myFile = subirTemplateForm.getDocumentoPath();
			String nombreArchivo = myFile.getFileName().substring(0, myFile.getFileName().lastIndexOf("."));
			String tipoArchivo = myFile.getFileName().substring(myFile.getFileName().lastIndexOf("."));
			doc.setNombre(nombreArchivo);
			doc.setType(tipoArchivo);
			String fileName = myFile.getFileName();
			byte[] fileData = myFile.getFileData();
			File test= new File("C:/misDemandas");
			if(!test.isDirectory()){
				test.mkdir();
				File test2= new File("C:/misDemandas/"+user.getIdUsuario());
				if(!test2.isDirectory()){
					test2.mkdir();
				}
			}else{
				File test2= new File("C:/misDemandas/"+user.getIdUsuario());
				if(!test2.isDirectory()){
					test2.mkdir();
				}
			}
			String filePath = "C:/misDemandas/"+user.getIdUsuario()+"/"+nombreArchivo+"_"+subirTemplateForm.getFecha().replaceAll("/", "")+tipoArchivo;
			doc.setPath(filePath);
			if (!fileName.equals("")) {
				File fileToCreate = new File(filePath);
				if (!fileToCreate.exists()) {
					FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
					fileOutStream.write(fileData);
					fileOutStream.flush();
					fileOutStream.close();
					DBAcciones.subirDocumento(doc);
					return mapping.findForward("display");
				}else{
					return mapping.findForward("existeArchivo");
				}
			}else{
				return mapping.findForward("errorDesconocido");
			}
		}else{
			subirTemplateForm.setAutos("");
			subirTemplateForm.setFecha("");
			return mapping.findForward("display");
		}
	}

}
